package pe.edu.unmsm.fisi.sisconteg.view.controller.login;

import java.io.IOException;

import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import pe.edu.unmsm.fisi.sisconteg.business.service.UsuarioService;
import pe.edu.unmsm.fisi.sisconteg.domain.model.Usuario;

@ManagedBean
@RequestScoped
@Component
public class LogeoController {

	/***************** ATRIBUTOS **************/
	private Usuario usuario;
	private String nick;
	private String pass;
	private String paginaActual;
	private String urlMenu = "";

	@Autowired
	@Qualifier("authenticationManager")
	private AuthenticationManager authenticationManager;

	@Resource
	private UsuarioService usuarioService;

	/***************** INICIALIZACION **************/
	public LogeoController() {
		usuario = new Usuario();
	}

	/***************** NAVEGACION **************/
	protected HttpServletRequest getRequest() {
		ExternalContext context = FacesContext.getCurrentInstance()
				.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) context.getRequest();
		return request;
	}

	public String loginAction() {
		String mensaje;
		String resultNavigation = null;
		try {
			Authentication antes = new UsernamePasswordAuthenticationToken(
					nick, pass);
			Authentication result = authenticationManager.authenticate(antes);
			SecurityContextHolder.getContext().setAuthentication(result);
		} catch (AuthenticationException e) {
			mensaje = e.getMessage();
			FacesMessage facesMessage = new FacesMessage(mensaje);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
			return null;
		}

		usuario = usuarioService.obtenerUsuarioxNick(nick);
		switch (usuario.getPerfil()) {
		case "ROLE_EGRESADO":
			resultNavigation = "egresadoPrincipal";
			break;

		case "ROLE_ADMIN":
			resultNavigation = "adminPrincipal";
			break;
		}

		FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
				.put("usuarioLogueado", usuario);

		return resultNavigation;
	}

	public String logoutAction() {
		// try {
		// HttpSession se2 = (HttpSession) FacesContext.getCurrentInstance()
		// .getExternalContext().getSession(false);
		// se2.invalidate();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		nick = "";
		pass = "";

		ExternalContext context = FacesContext.getCurrentInstance()
				.getExternalContext();
		try {
			context.redirect(context.getRequestContextPath() + "/logout");
		} catch (IOException e) {
			e.printStackTrace();
		}

		context.invalidateSession();

		FacesContext.getCurrentInstance().responseComplete();
		return null;
	}

	public String ingresoEgresadosAction(){
		return "ingresoEgresados";
	}
	
	public String iraReporteAction(){
		return "reporteResultBusqueda";
	}
	/***************** GETTERS AND SETTERS **************/
	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	public String getPaginaActual() {
		return paginaActual;
	}

	public void setPaginaActual(String paginaActual) {
		this.paginaActual = paginaActual;
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(
			AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	public String getUrlMenu() {
		return urlMenu;
	}

	public void setUrlMenu(String urlMenu) {
		this.urlMenu = urlMenu;
	}

	public String getNick() {
		return nick;
	}

	public void setNick(String nick) {
		this.nick = nick;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

}
